﻿using Cirrious.MvvmCross.Commands;
using Cirrious.MvvmCross.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using TealightV5.Models;

namespace TealightV5.ViewModels
{
    public class HomeViewModel : BaseViewModel
    {
        private string _searchText;

        private ObservableCollection<Article> articleList = new ObservableCollection<Article>();

        public HomeViewModel()
        {
            PickRandomSearchTerm();
            articleList.Add(new Article() { Title = "Hallo dit is een article" });
        }

        public ObservableCollection<Article> ArticleList
        {
            get { return articleList; }
            set { articleList = value; }
        }

        public ICommand PickRandomCommand
        {
            get
            {
                return new MvxRelayCommand(PickRandomSearchTerm);
            }
        }

        public ICommand SearchCommand
        {
            get
            {
                return new MvxRelayCommand(DoSearch);
            }
        }

        public string SearchText
        {
            get { return _searchText; }
            set { _searchText = value; RaisePropertyChanged("SearchText"); }
        }

        public void DoSearch()
        {
            ArticleFinder.StartAsyncSearch(SearchText, Success, Error);
        }

        public void Error(Exception e)
        {
            throw e;
        }

        public void Success(IEnumerable<Article> articles)
        {
            //InvokeOnMainThread(() => DisplayTweets(enumerable));
            InvokeOnMainThread(() =>
            {
                foreach (var art in articles)
                {
                    articleList.Add(art);
                }
            });
        }

        private void PickRandomSearchTerm()
        {
            var items = new[] { "*", "nummer" };
            var r = new Random();
            var originalText = SearchText;
            var newText = originalText;
            while (originalText == newText)
            {
                var which = r.Next(items.Length);
                newText = items[which];
            }
            SearchText = newText;
        }
    }
}